<?php

/**
 * 花集通淘宝交易API(为了方便视图呈现，重新调整数据层级等)
 *
 * @author cjj
 */
class TradeAPI {

    private $_client;

    /**
     * Constructor
     */
    public function __construct($options = array()) {
        $client = isset($options[0]) ? $options[0] : null;
        if (!$client || !$client instanceof TaobaoClient) {
            throw new APIException(10001, '淘宝API 客户端载入失败');
        }
        $this->_client = $client;
    }

    /**
     * 获取列表数据（不自动获取交易详情）
     * @param int   $page
     * @param int   $page_size
     * @param int   $type
     * @param array $options
     *
     * @return array
     * @throws APIException
     */
//    public function getData($page = 1, $page_size = 100, $type=0,$options = array()) {
//        $use_has_next = isset($options['use_has_next']) ? $options['use_has_next'] : 'false';
//        $paras = array(
//            'fields' => 'tid,status',
//            'page_no' => $page,
//            'page_size' => $page_size,
//            'use_has_next' => $use_has_next
//        );
//        $paras=array_merge($paras,$options);
//        if($type===0){
//            $jsonData = $this->_client->api('taobao.trades.sold.get', $paras);
//            $result = $this->_parseGetResponse($jsonData, 'trades_sold_get');
//        }
//        else{
//            $jsonData = $this->_client->api('taobao.trades.sold.increment.get', $paras);
//            $result = $this->_parseGetResponse($jsonData, 'trades_sold_increment_get');
//        }
//        return $result;
//    }
    public function getData($start_modified, $end_modified, $page) {
        $use_has_next = isset($options['use_has_next']) ? $options['use_has_next'] : 'false';
        $paras = array(
            'fields' => 'tid,status',
            'page_no' => $page,
            'start_modified' => $start_modified,
            'end_modified' => $end_modified,
        );
        $jsonData = $this->_client->api('taobao.trades.sold.increment.get', $paras);
        $result = $this->_parseGetResponse($jsonData, 'trades_sold_increment_get');
        return $result;
    }

    /**
     * 获取增量列表
     *
     * @param int $page
     * @param int $page_size
     * @param array $options
     *
     * @return array
     * @throws APIException
     */
    public function getIncrementList($page = 1, $page_size = 100, $options = array()) {
        $use_has_next = isset($options['use_has_next']) ? $options['use_has_next'] : 'false';
        $paras = array(
            'fields' => 'tid',
            'page_no' => $page,
            'page_size' => $page_size,
            'use_has_next' => $use_has_next
        );
        if (isset($options['status']) && $options['status']) {
            $paras['status'] = $options['status'];
        }
        if (isset($options['type']) && $options['type']) {
            $paras['type'] = $options['type'];
        }
        if (isset($options['start_modified']) && $options['start_modified']) {
            $paras['start_modified'] = $options['start_modified'];
        }
        if (isset($options['end_modified']) && $options['end_modified']) {
            $paras['end_modified'] = $options['end_modified'];
        }
        $jsonData = $this->_client->api('taobao.trades.sold.increment.get', $paras);
        //BEGIN{将淘宝数据格式 转化为花集通 标准数据格式 array('total_records'=>'记录数','data'=>'数据列表')
        $result = $this->_parseGetResponse($jsonData, 'trades_sold_increment_get');
        //}END
        if (isset($result['data']) && isset($result['data']['trades']) && $result['data']['trades']) {
            foreach ($result['data']['trades'] as &$trade) {
                if (isset($trade['tid']) && $trade['tid']) {
                    $data = $this->getFullInfoById($trade['tid']);
                    $trade = array_merge($trade, $data);
                }
            }
        }
        return $result;
    }

    /**
     * 获取交易列表信息
     *
     * @param int $page
     * @param int $page_size
     * @param array $options
     *
     * @return mixed
     */
    public function getList($page = 1, $page_size = 100, $options = array(), $exist_data = array()) {
        $use_has_next = isset($options['use_has_next']) ? $options['use_has_next'] : 'false';
        $paras = array(
            'fields' => 'tid',
            'page_no' => $page,
            'page_size' => $page_size,
            'use_has_next' => $use_has_next
        );
        if (isset($options['status']) && $options['status']) {
            $paras['status'] = $options['status'];
        }
        if (isset($options['buyer_nick']) && $options['buyer_nick']) {
            $paras['buyer_nick'] = $options['buyer_nick'];
        }
        if (isset($options['start_created']) && $options['start_created']) {
            $paras['start_created'] = $options['start_created'];
        }
        if (isset($options['end_created']) && $options['end_created']) {
            $paras['end_created'] = $options['end_created'];
        }
        $jsonData = $this->_client->api('taobao.trades.sold.get', $paras);
        //BEGIN{将淘宝数据格式 转化为花集通 标准数据格式 array('total_records'=>'记录数','data'=>'数据列表')
        $result = $this->_parseGetResponse($jsonData, 'trades_sold_get');
        //}END
//        if (isset($result['data']) && isset($result['data']['trades']) && $result['data']['trades']) {
//            foreach ($result['data']['trades'] as $key => &$trade) {
//                if (isset($trade['tid']) && $trade['tid']) {
//                    if ($exist_data && isset($exist_data[$trade['tid']])) {//echo($trade['tid'] .' remove ==> '.$exist_data[$trade['tid']]."\n");
//                        unset($result['data']['trades'][$key]); //移除已存在的记录
//                        continue;
//                    }
//                    $data = $this->getFullInfoById($trade['tid']);
//                    if($data && is_array($data)){
//                        $trade = array_merge($trade, $data);
//                    }
//                    else{
//                        //TODO:未读取到的DATA
//                    }
//                }
//            }
//        }
        return $result;
    }

    /**
     * 获取交易详细信息
     *
     * @param $tid
     *
     * @return array|bool|mixed|string
     */
    public function getFullInfoById($tid) {
        $paras = array(
            'fields' => 'tid,status,created,pay_time,modified,consign_time,buyer_nick,buyer_message, buyer_memo,post_fee,total_fee, payment,
                seller_flag,seller_memo,consign_time,title,
                receiver_name, receiver_state,receiver_city, receiver_district, receiver_address, receiver_mobile,
                receiver_phone,receiver_zip,
                orders.adjust_fee,orders.buyer_rate,orders.discount_fee,orders.end_time,orders.num,orders.num_iid,orders.oid,
                orders.order_from,orders.outer_iid,orders.payment,orders.pic_path,orders.price,orders.refund_status,
                orders.seller_rate,orders.seller_type,orders.sku_properties_name,orders.status,orders.title,
                orders.total_fee,discount_fee,
                promotion_details',
            'tid' => $tid
        );
        $result = $this->_client->api('taobao.trade.fullinfo.get', $paras);
        if ($result) {
            $result = $this->_parseGetResponse($result, 'trade_fullinfo_get');
        }
        return $result;
    }

    /**
     * 根据淘宝TID 获取交易数据
     *
     * @param $tid
     *
     * @return mixed
     */
    public function getOrderByTid($tid) {
        return $this->_client->api('taobao.trade.fullinfo.get', array(
                    'fields' => 'tid,title,created,pay_time,seller_flag,buyer_nick,buyer_memo,buyer_message,
                    buyer_email,buyer_area, post_fee,payment,status, seller_memo,
                    receiver_name,receiver_state, receiver_city, receiver_district, receiver_address,receiver_mobile,
                    receiver_phone,receiver_zip,orders.title, orders.pic_path, orders.price, orders.num,
                    orders.num_iid,  orders.status, orders.oid, orders.payment,orders.sku_properties_name,
                    credit_card_fee',
                    'tid' => $tid
        ));
    }

    /**
     * 根据淘宝TID 获取交易数据
     *
     * @param $nid
     *
     * @return mixed
     */
    public function getSkuByNid($nid) {
        return $this->_client->api('taobao.item.skus.get', array(
                    'fields' => 'properties_name',
                    'tid' => $nid
        ));
    }

    /**
     * 更新备注
     *
     * @param $tid
     * @param $memo
     * @param $flag
     *
     * @return mixed
     */
    public function updateMemo($tid, $memo, $flag = null) {
        $paras = array();
        if ($flag !== null && $flag >= 0) {
            $paras['flag'] = $flag;
        }
        if (!empty($memo)) {
            $paras['memo'] = $memo;
        }
        if (!$paras) {
            return null;
        }
        $paras['tid'] = $tid;
        return $this->_client->api('taobao.trade.memo.update', $paras);
    }

    /**
     * 修改收货信息
     *
     * @param $tid
     * @param $paras
     *
     * @return mixed
     */
    public function updateShippingAddress($tid, $paras) {
        $paras['tid'] = $tid;
        $result = $this->_client->api('taobao.trade.shippingaddress.update', $paras);
        return $result;
    }

    /**
     * 处理淘宝交易数据
     *
     * @param $jsonData
     * @param $response_name
     *
     * @return array
     * @throws APIException
     */
    private function _parseGetResponse($jsonData, $response_name) {
        if (isset($jsonData['error_response'])) {
            $errorResponse = $jsonData['error_response'];
            $msg = isset($errorResponse['sub_msg']) ? $errorResponse['sub_msg'] : $errorResponse['msg'];
            return array();
////            throw new APIException(10000, $msg, $errorResponse);
        }
        $response_name.='_response';
        $jsonData = isset($jsonData[$response_name]) ? $jsonData[$response_name] : $jsonData;
        if(isset($jsonData['total_results']) && $jsonData['total_results'] == 0){
            return array();
        }
        $trades = isset($jsonData['trades']) ? $jsonData['trades'] : $jsonData;
        unset($jsonData['trades']);
        $structure = isset($construct['trade']) ? $construct['trade'] : array();
        $data = isset($trades['trade']) ? array_merge($structure, $trades['trade']) : $trades;
        if (isset($jsonData['total_results']) || (isset($jsonData['has_next']))) {
            foreach ($data as &$trade) {
                if (!$trade) {
                    continue;
                }
                $orders = isset($trade['orders']) ? $trade['orders'] : array();
                if ($orders) {
                    unset($trade['orders']);
                    $orders = isset($orders['order']) ? $orders['order'] : $orders;
                    if (!isset($orders[0])) {
                        $orders = array($orders);
                    }
                    $trade['orders'] = $orders;
                }
            }
            $result = array(
                'total_records' => isset($jsonData['total_results']) ? $jsonData['total_results'] : null,
                'data' => array('trades' => $data)
            );
            if (isset($jsonData['has_next']) && $jsonData['has_next']) {
                $result['has_next'] = $jsonData['has_next'];
            }
        } else {
            $orders = isset($data['orders']) ? $data['orders'] : array();
            if ($orders) {
                $orders = isset($orders['order']) ? $orders['order'] : $orders;
                if (!isset($orders[0])) {
                    $orders = array($orders);
                }
                $data['orders'] = $orders;
            }
            $promotionDetails = isset($data['promotion_details']) && $data['promotion_details'] ? $data['promotion_details'] : array();
            if ($promotionDetails) {
                $promotionDetails = isset($promotionDetails['promotion_detail']) ? $promotionDetails['promotion_detail'] : $promotionDetails;
                $promotionDetails = isset($promotionDetails[0]) ? $promotionDetails : array($promotionDetails);
                foreach ($promotionDetails as &$promotion) {
                    if (isset($promotion['promotion_desc']) && isset($promotion['promotion_id']))
                        unset($promotion['promotion_desc'], $promotion['promotion_id']);
                }
                $data['promotion_details'] = $promotionDetails;
            }
            $result = $data;
        }
        return $result;
    }

    /**
     * 根据淘宝TID获取产品id
     */
    public function getProductIDByNid($num_iid) {
        return $this->_client->api('taobao.item.get', array(
                    'fields' => 'product_id',
                    'num_iid' => $num_iid,
        ));
    }

    /**
     * 根据淘宝product_id获取产品
     */
    public function getProductById($product_id) {
        return $this->_client->api('taobao.product.get', array(
                    'fields' => 'pic_url,product_prop_imgs,property_alias',
                    'product_id' => $product_id,
        ));
    }

}
